package com.yida.gwj.common.utils;

import cn.hutool.core.date.DateUtil;

import java.time.*;
import java.util.*;

/**
 * 获取指定工作日后的日期 不包括法定假日
 *
 * @author wkz
 * @date 2023/04/13
 */
public class WeekdayUtils {


    /**
     * localDate转date
     *
     * @param localDate 当地日期
     * @return {@link Date}
     */
    private static Date localDateTransDate(LocalDate localDate){
        Instant instant = LocalDateTime.of(localDate, LocalTime.MIDNIGHT).atZone(ZoneId.systemDefault()).toInstant();
        return Date.from(instant);
    }

    /**
     * date转localDate
     *
     * @param date 日期
     * @return {@link Date}
     */
    private static LocalDate localDateTransDate(Date date){
        Instant instant = date.toInstant();
        ZonedDateTime zdt = instant.atZone(ZoneId.systemDefault());
        return zdt.toLocalDate();
    }


    /**
     * 获取明天的日期
     *
     * @param date
     * @return
     */
    private static Date getTomorrow(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, +1);
        date = calendar.getTime();
        return date;
    }

    /**
     * 获取 workNum个工作日后的日期
     *
     * @param today   今天
     * @param workNum 工作日数
     * @return {@link Date}
     */
    public static LocalDate targetDate(LocalDate today,Long workNum) {
        Date date = localDateTransDate(today);
        Date tomorrow = null;
        long delay = 1L;
        while(delay <= workNum){
            tomorrow = getTomorrow(date);
            //当前日期+1即tomorrow,判断是否是周末,不是则将已用日期+1,直到循环num次即可
            if(!DateUtil.isWeekend(tomorrow)){
                delay++;
            }
            date = tomorrow;
        }
        return localDateTransDate(date);
    }

    public static void main(String[] args) {
        System.out.println("本部门将在："+targetDate(LocalDate.parse("2023-04-13"), 5L)+"前办结该事项");
    }
}
